<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

// 创建数据库连接
try {
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 检查请求方法是否为 POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('只支持 POST 方法');
    }

    // 获取用户 ID（假设通过身份验证获取，例如从 JWT 或会话中获取）
    $user_id = $_POST['user_id'];
    if (empty($user_id)) {
        throw new Exception('用户 ID 不能为空');
    }

    // 获取文章信息
    $article_title = $_POST['article_title'] ?? '';
    if (empty($article_title)) {
        throw new Exception('文章标题不能为空');
    }

    $article_intro = $_POST['article_intro'] ?? '';
    $article_content = $_POST['article_content'] ?? '';
    if (empty($article_content)) {
        throw new Exception('文章内容不能为空');
    }

    $article_type = $_POST['article_type'] ?? '';
    $additional_link = $_POST['additional_link'] ?? '';
    $article_remark = $_POST['article_remark'] ?? '';
    $publish_time = date('Y-m-d H:i:s'); // 获取当前时间作为发布
    $likes = '0'; // 初始化获赞数量为 0
    $review_status = '假'; // 初始化审核状态为未审核
    $reviewer_id = ''; // 初始化审核者 ID 为空
    $rejection_reason = ''; // 初始化拒绝原因为空

    // 处理文章封面上传
    $article_cover = '';
    if (isset($_FILES['article_cover']) && $_FILES['article_cover']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['article_cover'];
        $file_name = basename($file['name']);
        $target_dir = 'uploads/';
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        $target_file = $target_dir . $file_name;
        if (!move_uploaded_file($file['tmp_name'], $target_file)) {
            throw new Exception('文章封面移动失败');
        }
        $article_cover = $target_file;
    }

    // 插入文章信息到数据库
    $insertArticle = "
        INSERT INTO mi_bbs (
            发布者用户的id,
            文章标题,
            文章介绍,
            文章内容,
            文章类型,
            获赞数量,
            文章封面,
            附加链接,
            文章备注,
            文章发布时间,
            是否已审核,
            审核者的用户id,
            拒绝原因
        ) VALUES (
            :user_id,
            :article_title,
            :article_intro,
            :article_content,
            :article_type,
            :likes,
            :article_cover,
            :additional_link,
            :article_remark,
            :publish_time,
            :review_status,
            :reviewer_id,
            :rejection_reason
        )
    ";

    $stmt = $pdo->prepare($insertArticle);
    $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
    $stmt->bindParam(':article_title', $article_title, PDO::PARAM_STR);
    $stmt->bindParam(':article_intro', $article_intro, PDO::PARAM_STR);
    $stmt->bindParam(':article_content', $article_content, PDO::PARAM_STR);
    $stmt->bindParam(':article_type', $article_type, PDO::PARAM_STR);
    $stmt->bindParam(':likes', $likes, PDO::PARAM_STR);
    $stmt->bindParam(':article_cover', $article_cover, PDO::PARAM_STR);
    $stmt->bindParam(':additional_link', $additional_link, PDO::PARAM_STR);
    $stmt->bindParam(':article_remark', $article_remark, PDO::PARAM_STR);
    $stmt->bindParam(':publish_time', $publish_time, PDO::PARAM_STR);
    $stmt->bindParam(':review_status', $review_status, PDO::PARAM_STR);
    $stmt->bindParam(':reviewer_id', $reviewer_id, PDO::PARAM_STR);
    $stmt->bindParam(':rejection_reason', $rejection_reason, PDO::PARAM_STR);
    $stmt->execute();

    // 获取插入的文章 ID
    $article_id = $pdo->lastInsertId();

    // 返回成功结果
    $result = [
        'status' => 'success',
        'message' => '文章添加成功',
        'data' => [
            'id' => $article_id,
            'article_title' => $article_title,
            'publish_time' => $publish_time
        ]
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    // 捕获异常并返回错误信息
    $errorResult = [
        'status' => 'error',
        'message' => '文章添加失败：' . $e->getMessage()
    ];
    echo json_encode($errorResult, JSON_UNESCAPED_UNICODE);
}
?>